<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class SysconfigCacheComponent extends Component
{

    public $_cache_config = 'sys_config';
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 按别名获取系统配置信息
     * @param  $attr  用户属性
     *
     * @return 用户属性信息
     */
    public function getVal($alias = null)
    {
        $key = 'sys_config';
        $data = Cache::read($key,$this->_cache_config);
        if ($data === false) {
            $this->createCache();
            $data = Cache::read($key,$this->_cache_config);
        }

        if (empty($data)) {
            return null;
        }

        if (empty($alias)) {
            return $data;
        }

        return $data[$alias];

    }

    /**
     * 创建系统配置信息缓存
     */
    public function createCache()
    {
        $key = 'sys_config';
        $controller = $this->_registry->getController();
        $controller->loadModel('SysConfigs');

        $data = $controller->SysConfigs->find()
            ->all();
        $config= [];
        foreach($data as $k=>$v) {
            $config[$v['alias']] = $v['value'];
        }
        Cache::write($key, $config, $this->_cache_config);
    }

}